import { ipcRenderer } from "electron";
import * as remote from "@electron/remote";
import { IpcMsg } from "@/mdesign-lib/mdesign-main.js";

/**
 * IpcWindow用于调用其他渲染进程的window
 *
 * 每个window都要提供一个唯一名称
 *
 * T是popup方法的参数类型，R是popup的返回值Promise<R>
 */
export class IpcWindow<T, R> {
  windowName = "";

  opened = false;
  mutiple?: boolean;

  constructor(windowName: string, mutiple?: boolean) {
    this.windowName = windowName;
    this.mutiple = mutiple;
  }

  popup(query?: T, onWindowChange?: (data: any) => void): Promise<R> {
    if (!this.mutiple && this.opened) {
      return Promise.resolve<any>({});
    }
    return new Promise(resolve => {
      ipcRenderer.send(IpcMsg.OpenWindow, { windowName: this.windowName, query });
      let changeCallBack: ((event: Electron.IpcRendererEvent, ...args: any[]) => void) | undefined;
      if (onWindowChange) {
        changeCallBack = async (event: Electron.IpcRendererEvent, data: any) => {
          try {
            await onWindowChange(data);
          } catch {
            this.abort();
          }
        };
      }
      const closeCallBack = (event: Electron.IpcRendererEvent, data: any) => {
        if (data && data.windowName === this.windowName) {
          console.log(data.windowName + " close");
          // 关闭浮窗窗口时需要将floatingWindowIdMap中删除对应记录
          if (data.windowName.indexOf("DiagramFloating") != -1) {
            if (app.global.floatingWindowIdMap.has(data.windowName)) {
              app.global.floatingWindowIdMap.delete(data.windowName);
            }
          }
          resolve(data);
          ipcRenderer.off(IpcMsg.WindowClose, closeCallBack);

          if (changeCallBack) {
            ipcRenderer.off(IpcMsg.WindowChange, changeCallBack);
          }
          this.opened = false;

          const browserWindow = remote.getCurrentWindow();
          browserWindow.focus();
        }
      };
      ipcRenderer.on(IpcMsg.WindowClose, closeCallBack);
      if (changeCallBack) {
        ipcRenderer.on(IpcMsg.WindowChange, changeCallBack);
      }
      this.opened = true;
    });
  }

  // // 对于一些获取数据较慢的情况，可先打开弹窗，再执行下面的方法发送参数, 只支持已经加载好的弹窗
  // sendParam(param: any) {
  //   ipcRenderer.send(IpcMsg.SendParam, { windowName: this.windowName, param });
  // }

  // 手动执行关闭窗口
  done() {
    ipcRenderer.send(IpcMsg.ManulCloseWindow, { windowName: this.windowName });
  }
  // 弹窗的后续操作出错后触发abort事件
  abort() {
    ipcRenderer.send(IpcMsg.WindowAbort, { windowName: this.windowName });
  }
}
